package org.snail.chat.service.chatchain.chain;


import lombok.NonNull;
import lombok.extern.log4j.Log4j;
import org.apache.log4j.Logger;
import org.snail.chat.service.chatchain.dao.ChatCreateOrUpdateDAO;
import org.snail.dept.bean.TreeNode;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 获取当群组管理员,如果当前群组没有管理员，就往上层找
 */
@Log4j
public class ManagerChatCreateOrUpdateHandler extends ChatCreateOrUpdateHandler {
    int count = 5;

    private final Logger LOGGER = Logger.getLogger(ManagerChatCreateOrUpdateHandler.class);

    //TODO 传值存在问题 treeNode
    @Override
    public void doCreateOrUpdate(TreeNode treeNode, @NonNull Map<String, ChatCreateOrUpdateDAO> chatCreateOrUpdateDAOMap) throws Exception {

        //获取当前树的ChatCreateOrUpdateDAO
        ChatCreateOrUpdateDAO chatCreateOrUpdateDAO = getChatCreateOrUpdateDAO(treeNode, chatCreateOrUpdateDAOMap);

        //获取上级部门manager
        List<String> managerList = new ArrayList<String>();
        getTopManagers(managerList, treeNode, 10);
        log.info(chatCreateOrUpdateDAO.getName() + " managerList : " + managerList);
        //添加Manager列表到需要添加的队列中
        addUserChatCreateOrUpdateDAO(chatCreateOrUpdateDAO, managerList);

        //重新放回到Map中
        chatCreateOrUpdateDAOMap.put(treeNode.getId(), chatCreateOrUpdateDAO);
    }

    /**
     * 获取上级部门的Manager
     * @param managerList
     * @param treeNode
     * @param loopCount
     */
    private void getTopManagers(List<String> managerList, TreeNode treeNode, int loopCount) {
        if(null!=treeNode && loopCount>=0) {
            //层数减少
            loopCount--;

            //执行当前节点逻辑
            if(null!=treeNode) {

                List<String> curentManagerList = treeNode.getManager();
                if(null!=curentManagerList && !curentManagerList.isEmpty()) {
                    if(null==managerList) {
                        managerList = new ArrayList<String>();
                    }
                    managerList.addAll(curentManagerList);
                }

                //获取上级部门的Manager
                TreeNode parentTreeNode = treeNode.getParentNode();
                if(null!=parentTreeNode) {
                    getTopManagers(managerList, parentTreeNode, loopCount);
                }
            }
        }
    }

}
